package com.zt.bus.assistant.service;

import com.zt.bus.assistant.inter.ContactUsMapper;
import com.zt.bus.assistant.model.ContactUs;
import com.zt.servlet.ReqBean;
import com.zt.system.model.BusinessException;
import com.zt.system.model.SqlBuilder;
import com.zt.system.service.BaseService;
import com.zt.util.DateUtil;
import com.zt.util.StringUtil;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class ContactUsService extends BaseService {

    @Autowired
    private ContactUsMapper contactUsMapper;

    /**
     * 查询
     *
     * @param reqBean
     * @return
     */
    public JSONObject findContactUs(ReqBean reqBean) {
        SqlBuilder sqlBuilder = new SqlBuilder("select *  from DZ_CONTACT_US n where 1=1", new Object[0]);
        return this.queryTable(sqlBuilder, reqBean.getPageSize(), reqBean.getPageIndex());
    }

    /**
     * 新增
     *
     * @param reqBean
     */
    public void addContactUs(ReqBean reqBean) {
    	ContactUs contactUs = getContactUs(reqBean);
    	contactUs.setId(intIncrementId("DZ_CONTACT_US", "ID"));// 手动设置Id
    	contactUs.setMakeTime(contactUs.getModifyTime());
        contactUsMapper.insert(contactUs);
    }

    /**
     * 修改
     *
     * @param reqBean
     */
    public void updateContactUs(ReqBean reqBean) {
        String id = reqBean.getInfo("id");
        if (StringUtil.isEmpty(id)) {
            throw new BusinessException("获取主键失败");
        }
        ContactUs contactUs = getContactUs(reqBean);
        contactUsMapper.updateByPrimaryKeySelective(contactUs);
    }

    /**
     * 删除
     *
     * @param reqBean
     */
    public void removeContactUs(ReqBean reqBean) {
        String id = reqBean.getInfo("id");
        if (StringUtil.isEmpty(id)) {
            throw new BusinessException("获取主键失败");
        }
        contactUsMapper.deleteByPrimaryKey(id);
    }

    /**
     * 从表单获取对象
     *
     * @param reqBean
     * @return
     */
    private ContactUs getContactUs(ReqBean reqBean) {
    	ContactUs contactUs = new ContactUs();

    	contactUs.setId(reqBean.getInfo("id"));
    	contactUs.setContent(reqBean.getInfo("content"));
    	contactUs.setAndroidContent(reqBean.getInfo("androidContent"));
    	contactUs.setStatus(reqBean.getInfoInt("status"));
    	contactUs.setOperator(reqBean.getUserId());
    	contactUs.setMakeTime(DateUtil.parseDateTime(reqBean.getInfo("makeTime")));
    	contactUs.setModifyTime(new Date());
    	contactUs.setRemark(reqBean.getInfo("remark"));

        return contactUs;
    }

    public JSONObject query4Mobile(ReqBean reqBean) {
        String sql = "select *  from DZ_CONTACT_US";
        if(query(sql).size() > 0) {
            return query(sql).getJSONObject(0);
        } else {
            return null;
        }
    }
}